﻿#include "core/app_manager.h"

namespace vz {

AppManager::AppManager() {
  main_event_service_ = EventService::GetCurrentEventService();
}

bool AppManager::Register(AppInterface::Ptr app) {
  EventService::Ptr event_service = EventService::CreateEventService();
  app->SetEventService(event_service);
  apps_.push_back(app);
  return true;
}

bool AppManager::Run() {
  for (std::list<AppInterface::Ptr>::iterator iter = apps_.begin();
       iter != apps_.end();
       ++iter) {
    AppInterface::Ptr app = *iter;
    if (!app->PreInit()) {
      LOG(LS_ERROR) << "PreInit " << app->GetAppName() << " failed!";
      return false;
    }
  }

  for (std::list<AppInterface::Ptr>::iterator iter = apps_.begin();
       iter != apps_.end();
       ++iter) {
    AppInterface::Ptr app = *iter;
    if (!app->Init()) {
      LOG(LS_ERROR) << "Init " << app->GetAppName() << " failed!";
      return false;
    }
  }

  for (std::list<AppInterface::Ptr>::iterator iter = apps_.begin();
       iter != apps_.end();
       ++iter) {
    AppInterface::Ptr app = *iter;
    if (!app->Run()) {
      LOG(LS_ERROR) << "Run " << app->GetAppName() << " failed!";
      return false;
    }
  }

  main_event_service_->Run();
  return true;
}

void AppManager::OnMessage(Message* msg) {

}

}  // namespace vz
